# -*- coding: utf-8 -*-
"""
-------------------------------------------------
  Description :
  Author :    Administrator
  date：     2021/10/10
-------------------------------------------------
  Change Activity:
          2021/10/10:
-------------------------------------------------
"""
import json
import os
import re
import uuid

import requests
from Api.BookAccountNumberManage.ocr import ocr_img
from Api.BookAccountNumberManage.retry_model import MyRetry
from Config.config import IMAGE_DIR, logger
from Api.BookAccountNumberManage.get_proxy import get_proxy
from Api.Request2_new import Request2
from Api.my_request import my_requests

from Api.BookAccountNumberManage.redis_client import redis_client

redis_client = redis_client.redis_pool


class RefreshCookie:
    def __init__(self):
        self.cookie = {}
        self.head = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
        }
        os.makedirs(IMAGE_DIR) if not os.path.isdir(IMAGE_DIR) else ''

    @MyRetry(times=5, return_obj=False)
    def download_and_ocr_img(self):
        try:
            # res = requests.get('http://www.ucdrs.superlib.net/user/vImage.jsp', headers=self.head, cookies=self.cookie, timeout=15,proxies=get_proxy())
            res = Request2.send_request('http://www.ucdrs.superlib.net/user/vImage.jsp', headers=self.head, cookies=self.cookie, timeout=15)
            code_path = os.path.join(IMAGE_DIR, f'{uuid.uuid4()}.jpg')
            with open(code_path, 'wb') as f:
                f.write(res.content)
            code = ocr_img(code_path)
            if code:
                return code
            else:
                raise ValueError('ocr失败')
        except Exception as e:
            raise ValueError(e)
        finally:
            if os.path.isfile(code_path):
                os.remove(code_path)

    @MyRetry(times=2, return_obj=False)
    def try_login(self, username, password, login_url, S):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "Origin": "http://www.ucdrs.superlib.net",
            "Referer": "http://www.ucdrs.superlib.net/login/login.action",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"
        }
        data = {
            "backurl": "",
            "gid": "7320",
            "areaid": "431",
            "userName": username,
            "passWord": password
        }
        # res = Request2.send_request(login_url, method='post', data=data, headers=headers, cookies=self.cookie, allow_redirects=True, timeout=20)
        S, res = my_requests.post(login_url, data=data, headers=headers, session=S, return_s=True)
        if res.status_code == 200:
            url = "http://book.ucdrs.superlib.net/jsarea.jsp"
            params = {
                "username": username
            }
            S, res = my_requests.get(url, params=params, session=S, return_s=True)
            logger.info(f'用户: {username} 登录成功')
            self.cookie.update(S.cookies.get_dict())
            return True
        elif res.status_code != 200:
            if '登录错误次数过多，账号已被锁定，请10分钟后再登录' in res.text:
                logger.error(f'用户: {username} 登录失败   反馈: 登录次数过多')
                return False

            cause = re.search(r'id="msg">([^<]*)</font>', res.text)
            cause = cause[1] if cause else ''
            # logger.debug(f'用户: {username} 登录失败  验证码: {code}  反馈: {cause}')
            logger.debug(f'用户: {username} 登录失败  反馈: {cause}')
            if '验证码有误' in cause:
                return False
            else:
                raise ValueError(f'登录失败 > {cause}')
        else:

            raise ValueError(f'登录失败，状态码: {res.status_code}')

    @MyRetry(times=5, return_obj=False)
    def add_cookie(self, username, login_url):
        if "userName_dsr" in self.cookie:
            redis_client.set(f'duxiu_cookie:{username}', json.dumps(self.cookie), ex=int(365 * 24 * 60 * 60))
            logger.info(f'用户:{username} cookies更新完成')
            return True
        else:
            return False

    @MyRetry(times=5, return_obj=False)
    def login(self, username, password):
        logger.info(f'开始登录用户：{username}')
        login_url = 'http://www.ucdrs.superlib.net/login/login.action'
        head = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Host': 'www.ucdrs.superlib.net',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
            'Pragma': 'no-cache',
            'Proxy-Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1'
        }
        S = requests.Session()
        S, res = my_requests.get(login_url, headers=head, timeout=20, session=S, return_s=True)

        self.cookie = {i[0]: i[1] for i in res.cookies.items()}
        if not self.cookie:
            raise ValueError('获取cookie失败')
        times = 0
        while True:
            if times == 10:
                logger.warning(f'尝试10次未登录成功 {username}')
                return False
            else:
                times += 1
            try_res = self.try_login(username, password, login_url, S)
            if not try_res:
                break
            add_res = self.add_cookie(username, login_url)
            if not add_res:
                raise ValueError('补全cookie失败')
            else:
                return True


refresh = RefreshCookie()
if __name__ == '__main__':
    user_list = {
        'CL13297040870': 'BXTYCRq941754&',
    }

    for user, pwd in user_list.items():
        # refresh.login('pw15525796698', 'qq123456.')
        refresh.login(user, pwd)
